using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Inspections.Commands;

/// <summary>
/// 自动点检项创建命令。
/// </summary>
/// <param name="Item"></param>
public sealed record CreateAutoInspectionItemCommand(EquipAutoInspectionItemDto Item) : IRequest<IResult<bool>>;

internal sealed class CreateAutoInspectionItemCommandHandler(IRepository<EquipAutoInspectionItem> repo) : IRequestHandler<CreateAutoInspectionItemCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateAutoInspectionItemCommand request, CancellationToken cancellationToken)
    {
        // 点检项不能重名
        if (await repo.IsAnyAsync(m => m.PlanId == request.Item.PlanId && m.SubjectName == request.Item.SubjectName, cancellationToken))
        {
            return Result.Failure("点检项名称已存在");
        }

        var item = request.Item.Adapt<EquipAutoInspectionItem>();
        var ok = await repo.InsertAsync(item, cancellationToken);
        return Result.From(ok);
    }
}
